home *** CD-ROM | disk | FTP | other *** search
Text File | 1992-05-29 | 2.1 KB | 68 lines | [TEXT/MPS ] |
- ############################################################################
- #
- # Name: isort.icn
- #
- # Title: Customizable sort procedure
- #
- # Author: Robert J. Alexander
- #
- # Date: April 3, 1992
- #
- ############################################################################
- #
- # Customizable sort procedure for inclusion in Icon programs.
- #
- # isort(x,keyproc,y)
- #
- # Argument x can be any Icon data type that is divisible into elements
- # by the unary element generation (!) operator. The result is a list
- # of the objects in sorted order.
- #
- # The default is to sort elements in their natural, Icon-defined order.
- # However, an optional parameter (keyproc) allows a sort key to be
- # derived from each element, rather than the default of using the
- # element itself as the key. Keyproc can be a procedure provided by
- # the caller, in which case the first argument to the key procedure is
- # the item for which the key is to be computed, and the second argument
- # is isort's argument y, passed unchanged. The keyproc must produce
- # the extracted key. Alternatively, the keyproc argument can be an
- # integer, in which case it specifies a subscript to be applied to each
- # item to produce a key. Keyproc will be called once for each element
- # of structure x.
- #
- #
- #
-
- procedure isort(x,keyproc,y)
- local items,item,key,result
- if not ((\function)() == "sortf") then return old_isort(x,keyproc,y)
- if /keyproc | integer(keyproc) then return sortf(x,keyproc)
- items := []
- every item := !x do
- put(items,[keyproc(item,y),item])
- items := sortf(items,1)
- result := []
- while put(result,get(items)[2])
- return result
- end
-
- #
- # This old version of isort works in Icon implementations not containing
- # the sortf() function.
- #
- procedure old_isort(x,keyproc,y)
- local items,item,key,result
- if y := integer(keyproc) then
- keyproc := proc("[]",2)
- else /keyproc := 1
- items := table()
- every item := !x do {
- key := keyproc(item,y)
- (/items[key] := [item]) | put(items[key],item)
- }
- items := sort(items,3)
- result := []
- while get(items) do every put(result,!get(items))
- return result
- end
-